﻿
var map = null;
var marker = null;
function pick() {
		$("#tipinput")[0].focus();
    map = new AMap.Map("container", {
        resizeEnable: true
    });
    //为地图注册click事件获取鼠标点击出的经纬度坐标
    var clickEventListener = map.on('click', function(e) {
        displayLocation(e.lnglat);
				marker.setPosition(e.lnglat);
    });
    var auto = new AMap.Autocomplete({
        input: "tipinput"
    });
    AMap.event.addListener(auto, "select", select);//注册监听，当选中某条记录时会触发

		marker = new AMap.Marker({
		    	draggable: true,
		      cursor: 'move',
				  raiseOnDrag: true
				});

		$("#lnglat").val(map.getCenter().getLng() + ',' + map.getCenter().getLat());
		var isWindows = /windows|win32/i.test(navigator.userAgent);
		if(isWindows) {
				$("#lnglat").attr("readonly", false);
		}
			
		AMap.event.addListener(marker,'dragend',function(e){
				displayLocation(e.lnglat);
		});
		
		AMap.event.addListener(marker,'dragging',function(e){
				displayLocation(e.lnglat);			
		});
		
		marker.setMap(map);
		
    function select(e) {
        if (e.poi && e.poi.location) {
      	    map.setZoom(15);
            map.setCenter(e.poi.location);
            displayLocation(e.poi.location);        		
        		marker.setPosition(e.poi.location);
        }
    }
    
    $("#lnglat").keyup(queryViaEnter);
		map.setZoom(10);
}

function displayLocation(king) {
		$("#lnglat").val(king.getLng() + ',' + king.getLat());
		copyPosition();
}

function copyPosition() {
		document.getElementById("lnglat").select();
		document.execCommand("Copy");
}

function queryViaEnter() {
		var e = window.event;
		if (e.keyCode == "13") {
				var lngCommaLat = $.trim($("#lnglat").val());
				locateByLngCommaLat(lngCommaLat);
		}
}

function locateByLngCommaLat(lngCommaLat) {
		var king = 0;
		var arr = lngCommaLat.split(",");
		try {
				king = new AMap.LngLat(arr[0],arr[1]);
				map.setCenter(king);
		    marker.setPosition(king);
		} catch (ex) {
		 		alert("不是合法坐标：" + lngCommaLat);
		}
}